package ar.com.unlp.fi.lrs.persist;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import ar.com.unlp.fi.lrs.domain.Statement;

public class StatementDao extends AbstractDao {

	public void save(Statement statement) {

		statement.setTimestamp(new Date());

		try {

			session = HibernateUtil.getSessionFactory().openSession();

			tx = session.beginTransaction();

			session.saveOrUpdate(statement);

			tx.commit();

		} catch (Exception e) {
			logger.error("Error al persistir", e);
		} finally {
			//session.close();
		}

	}

	public Statement get(long id) {
		session = HibernateUtil.getSessionFactory().openSession();
		Statement statement = (Statement) session.get(Statement.class, id);
		tx = session.getTransaction();
		session.beginTransaction();
		tx.commit();
		return statement;
	}

	public List<Statement> getAll() {

		session = HibernateUtil.getSessionFactory().openSession();

		Criteria crit = session.createCriteria(Statement.class);

		List<Statement> statements = crit.list();

		return statements;
	}

	/**
	 * Retorna los statements para un id de actor dado.
	 * 
	 * @param idAgent
	 * 
	 * @return
	 */
	public List<Statement> getAll(long idAgent) {

		session = HibernateUtil.getSessionFactory().openSession();

		Criteria crit = session.createCriteria(Statement.class);
		crit.createAlias("actor", "agentAlias");
		crit.add(Restrictions.eq("agentAlias.id", idAgent));
		List<Statement> statements = crit.list();

		return statements;
	}

	public void update(Statement statement) {
		

		statement.setStored(new Date());

		try {

//			session = HibernateUtil.getSessionFactory().O;

			tx = session.beginTransaction();

			session.saveOrUpdate(statement);

			tx.commit();

		} catch (Exception e) {
			logger.error("Error al persistir", e);
		} finally {
			session.close();
		}

	}

}
